package org.carl.redis.delay.queue.config;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.carl.redis.delay.queue.annotation.EnableRedisDelayQueue;
import org.carl.redis.delay.queue.common.DelayQueueException;
import org.carl.redis.delay.queue.core.RedisDelayQueueCenter;
import org.carl.redis.delay.queue.core.RedisDelayQueueContext;
import org.carl.redis.delay.queue.iface.RedisDelayQueue;
import org.carl.redis.delay.queue.listener.RedisDelayQueueStarterListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;

/**
 * redis延迟队列
 *
 * @author Carl
 */
@ConditionalOnBean(annotation = EnableRedisDelayQueue.class)
@Configuration
@AutoConfigureOrder
@Slf4j
public class RedisDelayConfig implements RedisDelayQueueCenter {
    @Autowired
    private Environment env;
    @Resource
    private RedisTemplate redisTemplate;

    @Bean
    public RedisDelayQueueStarterListener redisDelayQueueStarterListener() {
        return new RedisDelayQueueStarterListener();
    }

    @Bean
    public RedisDelayQueueContext redisDelayQueueContext() {
        String appName = StrUtil.trim(env.getProperty("spring.application.name"));
        if(StrUtil.isBlank(appName)){
            throw new DelayQueueException("请指定spring.application.name");
        }
        /**传入redisTemplate实例, 第二个参数为项目名 projectName ;不同项目需要设置不一样**/
        return new RedisDelayQueueContext(redisTemplate, appName);
    }

    @Bean
    public RedisDelayQueue redisDelayQueue() {
        return redisDelayQueueContext().getRedisDelayQueue();
    }
}
